🎯 Introduction to Strings
In Java, strings are one of the most commonly used data types. A string is a sequence of characters that represents text. Unlike primitive data types, strings are objects in Java, which means they have their own methods and behaviors that make them powerful and flexible for text manipulation.
Key Definition: A String in Java is an object that represents a sequence of characters. Strings are immutable, meaning once created, their values cannot be changed.
String Characteristics
- Immutable: Once a String object is created, it cannot be changed
- Objects: Strings are objects, not primitive data types
- Dynamic: Can grow or shrink in size (through creating new objects)
- Unicode Support: Support for international characters
🔧 Creating Strings
There are two main ways to create strings in Java:
1. String Literal
String str1 = "Hello, World!";
String str2 = "Java Programming";
2. Using new Keyword
String str3 = new String("Hello, World!");
String str4 = new String("Java Programming");
Important Difference: When using string literals, Java uses a string pool to store and reuse string objects. When using the new keyword, a new object is always created in heap memory, even if the same value already exists.
String Pool Example
String s1 = "Hello"; // Stored in string pool
String s2 = "Hello"; // References same object as s1
String s3 = new String("Hello"); // New object in heap
String s4 = new String("Hello"); // Another new object in heap
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different objects)
System.out.println(s3 == s4); // false (different objects)
System.out.println(s1.equals(s3)); // true (same content)
📏 String Length and Access
Getting String Length
String text = "Java Programming";
int length = text.length(); // Returns 16
System.out.println("Length: " + length);
Accessing Characters
String text = "Hello";
char firstChar = text.charAt(0); // Returns 'H'
char lastChar = text.charAt(text.length() - 1); // Returns 'o'
// Iterating through characters
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
System.out.println("Character at index " + i + ": " + c);
}
Getting Character Codes
String text = "A";
int charCode = text.codePointAt(0); // Returns 65 (ASCII for 'A')
🔍 String Comparison
String comparison is a fundamental operation in Java. There are several ways to compare strings, each serving different purposes.
1. equals() Method
String s1 = "Hello";
String s2 = "Hello";
String s3 = "hello";
boolean result1 = s1.equals(s2); // true (case-sensitive)
boolean result2 = s1.equals(s3); // false (different case)
2. equalsIgnoreCase() Method
String s1 = "Hello";
String s2 = "hello";
boolean result = s1.equalsIgnoreCase(s2); // true (ignores case)
3. compareTo() Method
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Apple";
int result1 = s1.compareTo(s2); // Negative (s1 < s2)
int result2 = s2.compareTo(s1); // Positive (s2 > s1)
int result3 = s1.compareTo(s3); // Zero (s1 == s3)
4. compareToIgnoreCase() Method
String s1 = "Hello";
String s2 = "hello";
int result = s1.compareToIgnoreCase(s2); // 0 (ignores case)
| Method |
Purpose |
Case Sensitivity |
Return Value |
| equals() |
Content comparison |
Case-sensitive |
boolean |
| equalsIgnoreCase() |
Content comparison |
Case-insensitive |
boolean |
| compareTo() |
Lexicographical comparison |
Case-sensitive |
int (negative, zero, positive) |
| compareToIgnoreCase() |
Lexicographical comparison |
Case-insensitive |
int (negative, zero, positive) |
✂️ String Manipulation Methods
Substring Operations
String text = "Java Programming";
// Get substring from index 5 to end
String sub1 = text.substring(5); // " Programming"
// Get substring from index 0 to 4 (exclusive)
String sub2 = text.substring(0, 4); // "Java"
// Get substring from index 5 to 12 (exclusive)
String sub3 = text.substring(5, 12); // " Program"
Trimming and Case Conversion
String text = " Hello World ";
// Remove leading and trailing whitespace
String trimmed = text.trim(); // "Hello World"
// Convert to uppercase
String upper = text.toUpperCase(); // " HELLO WORLD "
// Convert to lowercase
String lower = text.toLowerCase(); // " hello world "
Replacing Characters and Substrings
String text = "Java is fun, Java is powerful";
// Replace all occurrences
String replaced1 = text.replace("Java", "Python");
// "Python is fun, Python is powerful"
// Replace first occurrence
String replaced2 = text.replaceFirst("Java", "Python");
// "Python is fun, Java is powerful"
// Replace using regex
String replaced3 = text.replaceAll("Java", "Python");
// "Python is fun, Python is powerful"
🔍 String Searching Methods
Finding Characters and Substrings
String text = "Java Programming Language";
// Find first occurrence
int index1 = text.indexOf("Java"); // 0
int index2 = text.indexOf("Program"); // 5
int index3 = text.indexOf("Python"); // -1 (not found)
// Find last occurrence
int index4 = text.lastIndexOf("a"); // 21
int index5 = text.lastIndexOf("Java"); // 0
// Find from specific position
int index6 = text.indexOf("a", 5); // 10
Checking String Content
String text = "Java123";
// Check if string starts with prefix
boolean starts1 = text.startsWith("Java"); // true
boolean starts2 = text.startsWith("123"); // false
// Check if string ends with suffix
boolean ends1 = text.endsWith("123"); // true
boolean ends2 = text.endsWith("Java"); // false
// Check if string contains substring
boolean contains = text.contains("va1"); // true
// Check if string is empty
boolean empty = "".isEmpty(); // true
boolean notEmpty = "Java".isEmpty(); // false
🔄 String Conversion Methods
Converting to Arrays
String text = "Java,Python,C++";
// Convert to character array
char[] charArray = text.toCharArray();
// ['J', 'a', 'v', 'a', ',', 'P', 'y', 't', 'h', 'o', 'n', ',', 'C', '+', '+']
// Split string into array
String[] parts = text.split(",");
// ["Java", "Python", "C++"]
// Split with limit
String[] parts2 = text.split(",", 2);
// ["Java", "Python,C++"]
Converting from Arrays
char[] chars = {'J', 'a', 'v', 'a'};
String fromChars = new String(chars); // "Java"
String[] words = {"Hello", "World"};
String joined = String.join(" ", words); // "Hello World"
Value Conversion
// Convert other types to string
String fromInt = String.valueOf(42); // "42"
String fromDouble = String.valueOf(3.14); // "3.14"
String fromBoolean = String.valueOf(true); // "true"
String fromChar = String.valueOf('A'); // "A"
📊 StringBuilder and StringBuffer
Since strings are immutable, frequent string modifications can be inefficient. Java provides StringBuilder and StringBuffer classes for mutable string operations.
StringBuilder
StringBuilder sb = new StringBuilder();
// Append operations
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.append("!");
System.out.println(sb.toString()); // "Hello World!"
// Insert at specific position
sb.insert(5, " Beautiful");
// "Hello Beautiful World!"
// Delete characters
sb.delete(5, 15);
// "Hello World!"
// Replace characters
sb.replace(6, 11, "Java");
// "Hello Java!"
// Reverse the string
sb.reverse();
// "!avaJ olleH"
StringBuffer vs StringBuilder
| Aspect |
StringBuilder |
StringBuffer |
| Thread Safety |
Not thread-safe |
Thread-safe (synchronized) |
| Performance |
Faster |
Slower due to synchronization |
| Use Case |
Single-threaded applications |
Multi-threaded applications |
| Introduced |
Java 5 |
Java 1.0 |
🎯 Common String Methods Reference
| Method |
Description |
Example |
| length() |
Returns the length of the string |
"Hello".length() → 5 |
| charAt(int index) |
Returns character at specified index |
"Hello".charAt(0) → 'H' |
| substring(int begin, int end) |
Returns substring from begin to end-1 |
"Hello".substring(1, 4) → "ell" |
| concat(String str) |
Concatenates specified string |
"Hello".concat("World") → "HelloWorld" |
| replace(char old, char new) |
Replaces all occurrences of character |
"Hello".replace('l', 'L') → "HeLLo" |
| toLowerCase() |
Converts string to lowercase |
"Hello".toLowerCase() → "hello" |
| toUpperCase() |
Converts string to uppercase |
"Hello".toUpperCase() → "HELLO" |
| trim() |
Removes leading and trailing whitespace |
" Hello ".trim() → "Hello" |
| split(String regex) |
Splits string based on regex |
"a,b,c".split(",") → ["a","b","c"] |
💡 Best Practices for String Handling
🎯 Use String Literals When Possible
Prefer string literals over new String() for better memory efficiency and automatic string pooling.
⚡ Use StringBuilder for Concatenation
When building strings in loops or with many concatenations, use StringBuilder instead of the + operator.
🔍 Use equals() for Comparison
Always use equals() or equalsIgnoreCase() for content comparison, not the == operator.
📏 Check for null Before Operations
Always check if a string is null before performing operations to avoid NullPointerException.
🔄 Use String.format() for Complex Formatting
For complex string formatting, use String.format() instead of manual concatenation.
🎨 Use StringBuilder for Thread-Safe Operations
In multi-threaded environments, use StringBuffer instead of StringBuilder for thread safety.
📝 Summary
Strings are fundamental objects in Java that represent sequences of characters. Understanding string handling is crucial for effective Java programming. Key concepts to remember include string immutability, the string pool, various comparison methods, and the use of StringBuilder and StringBuffer for mutable string operations.
Mastering string operations enables you to efficiently handle text processing, user input, file operations, and many other common programming tasks. The rich set of string methods provided by Java makes text manipulation powerful and convenient.
In the next lectures, we'll explore how strings integrate with other Java features and learn advanced string processing techniques for real-world applications.